package com.itheima.tanhua.filter;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.itheima.tanhua.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


//全局过滤器
@Order(-1)  //过滤器执行的顺序
@Component
public class MyGlobalFilter implements GlobalFilter {


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        //String[] uri = {"/user/login", "/user/loginVerification"};
        ServerHttpRequest request = exchange.getRequest();
        //获取当前路径
        String nowuri = request.getURI().getPath();
        //需要放行的一些路径  登录 注册 /system/users/verification,/system/users/login
        // if (StrUtil.equals(nowuri,"/user/login") || StrUtil.equals(nowuri,"/user/loginVerification")){
        if ("/user/login".equals(nowuri) || "/user/loginVerification".equals(nowuri) || "/system/users/verification".equals(nowuri) || "/system/users/login".equals(nowuri)) {
            //放行
            return chain.filter(exchange);
        }
        String token = request.getHeaders().getFirst("Authorization");
        if(!StringUtils.isEmpty(token)){
            token = token.replace("Bearer ", "");
        }
        Claims claims = AppJwtUtil.getClaimsBody(token);
        //有四种状态0 ,-1 有效      1 ,2 过期
        int i = AppJwtUtil.verifyToken(claims);
        String redisKey = "CHECK_ID";
        if (i == -1 || i == 0) {
            Object id = claims.get("id");
            //将当前用户的id存入redis中
            stringRedisTemplate.opsForValue().set(redisKey, ObjectUtil.toString(id));
            //存在就放行
            return chain.filter(exchange);
        }
        //不存在说明没有登录进来
        // 4.拦截
        // 4.1.禁止访问，设置状态码   为认证401
        exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
        // 4.2.结束处理
        return exchange.getResponse().setComplete();
    }
}
